<template>
  <div id="goods-catalog">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px"
          >
            <el-form-item>
              <el-input
                v-model.trim="formInline.id"
                placeholder="输入类目ID"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model.trim="formInline.title"
                placeholder="输入类目名称"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="formInline.level"
                placeholder="请选择类目级别"
                clearable
              >
                <el-option
                  v-for="item in optionsStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-cascader
                v-model="formInline.parentId"
                :options="options"
                :props="{ checkStrictly: true }"
                clearable></el-cascader>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                v-permission="'operation:category:query'"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(1)"
                v-permission="'operation:category:create'"
                >添加</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="tableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 列表数据 -->
            <el-table-column prop="value" label="类目ID" sortable>
            </el-table-column>
            <el-table-column prop="label" label="类目名">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.label}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="全类目名">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.fullName}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="父类目ID" prop="parent">
            </el-table-column>
            <el-table-column prop="level" label="级别">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.level|level}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="" label="标记图片"></el-table-column>
            <el-table-column prop="username" label="类目图片">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.picUrl!=undefined"
                  style="width: 80px; height: 80px"
                  :src="scope.row.picUrl"
                  fit="contain"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(2, scope.$index, scope.row)"
                  v-permission="'operation:category:update'"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'operation:category:delete'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width:85%"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="广告图片" prop="picUrl">
           <el-upload
              class="avatar-uploader"
              action="http://192.168.1.99:8080/upload/admin"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="ruleForm.picUrl" :src="ruleForm.picUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        <el-form-item label="父类目">
          <el-cascader
            v-model="ruleForm.parentId"
            ref="coupon"
            :options="options"
            :props="{ checkStrictly: true }"
            clearable
            class="relevance"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 对话框表单结束 -->
    </el-dialog>
  </div>
</template>

<script>
import goodscatalog from "@/api/goodscatalog";
import Paging from "../../components/Paging";
export default {
  components: {
    Paging,
  },
  data() {
    var validateTitle = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类目名不能为空"));
      } else {
        callback();
      }
    };
    return {
      optionsStatus: [
        //选项框状态
        {
          value: 0,
          label: "一级类目",
        },
        {
          value: 1,
          label: "二级类目",
        },
        {
          value: 2,
          label: "三级类目",
        },
      ],
      options: [], //选项框商品
      formInline: {
        //查询数据
        id: "", //类目ID
        title:"",//类目名
        level: null, //级别
        parentId:null//父类目ID
      },
      ruleForm: {
        //表单数据
        title: "",//类目名
        picUrl: "",//图片
        iconUrl:"",//类目图标
        level:0,//级别
        parentId:null//父类目ID
      },
      roledata: "", //选中的数据
      index: "", //选中的下标
      rules: {
        //表单验证
        title: [{ required: true, validator: validateTitle, trigger: "blur" }],
      },
      title: "创造", //对话框的名字
      dialogFormVisible: false, //对话框表单的隐藏显示
      tableData: [], //后台全部列表数据
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
    };
  },
  created: function() {
    //一开始的渲染数据
    this.onSubmit();
    goodscatalog.tree().then((res) => {
      console.log(res);
      this.options = this.getTreeData(res.data.data)
    });
  },
  filters: {
    level: function(value) {
      switch (value) {
        case 0:
          value = "一级类目";
          break;
        case 1:
          value = "二级类目";
          break;
        default:
          value = "三级类目";
          break;
      }
      return value;
    },
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      if (that.formInline.parentId!=null||that.formInline.parentId!=undefined) {//父类目的查询
          if (typeof(that.formInline.parentId)!="number") {//判断是数组还是数字
          this.formInline.parentId=this.formInline.parentId[that.formInline.parentId.length-1]//获取数组最后一个数据
        }
      }
      let data = Object.assign(
        { pageNo: that.paging.currentPage, limit: that.paging.pagesize },
        that.formInline
      );
      goodscatalog
        .categoryInquire(data)
          //查询接口封装
        .then((res) => {
          console.log(res);
          that.tableData = res.data.data.items; //获取数据赋值
          that.paging.total = res.data.data.total; //总条数
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getTreeData(data) {
      //递归方法
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          //children是数据库中的变量名
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children); //返回元素的子元素的集合有数据继续导出
        }
      }
      return data;
    },
    handleEdit(digit, index, row) {
      //编辑和添加
      console.log(row, index);
      let that = this;
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
      if (digit == 1) {
        this.title = "创造";
        that.ruleForm.parentId=[]
      } else {
        setTimeout(function() {
        //防止重置时没有数据
        that.title = "编辑";
        that.roledata = row;
        that.index = index;
        that.ruleForm.picUrl=row.picUrl
        that.ruleForm.title=row.label
        that.ruleForm.parentId=row.parent
        that.ruleForm.level=row.level
         }, 50);
      }
    },
    submitForm(formName) {
      //提交
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
             that.dialogFormVisible = false;
              if (that.title == "创造") {
                //添加
                that.addition();
              } else {
                //编辑
                that.compile();
              }
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      let that = this;
      this.ruleForm.parentId=this.ruleForm.parentId[that.ruleForm.parentId.length-1]//获取数组最后一个数据
      goodscatalog
        .addCategory(that.ruleForm) //添加封装接口
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.topTips( res.data.errmsg,"success")
            that.paging.total = that.paging.total + 1; //总共条数+1条
            that.onSubmit()
            that.tableData.push(that.ruleForm);
          } else {
            that.topTips( res.data.errmsg,"error")
          }
        });
    },
    compile() {
      //编制
      let that = this;
      if (typeof(that.ruleForm.parentId)!="number") {//判断是数组还是数字
         this.ruleForm.level =that.ruleForm.parentId.length//状态
         this.ruleForm.parentId=this.ruleForm.parentId[that.ruleForm.parentId.length-1]//获取数组最后一个数据
      }
      let data = Object.assign(that.ruleForm, { id : that.roledata.value });
      goodscatalog
        .updateCategory(
          //编制封装接口
          data
        )
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.topTips( res.data.errmsg,"success")
            that.onSubmit()
          } else {
            that.topTips( res.data.errmsg,"error")
          }
        });
    },
    handleDelete(index, row) {
      //删除
      console.log(row)
      let that = this;
      this.$confirm(
        "此操作将永久删除--" + row.label + "--, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          goodscatalog
            .deleteCategory({
              //删除封装接口
              id  : row.value,
            })
            .then(function(res) {
              console.log(res)
              if (res.data.errmsg == "成功") {
                that.topTips( res.data.errmsg,"success")
                that.paging.total = that.paging.total - 1; //总共条数-1条
                that.tableData.splice(index, 1);
              } else {
                that.topTips( res.data.errmsg,"error")
              }
            });
        })
        .catch(() => {
          this.topTips("已取消删除","info")
        });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 50);
    },
     handleAvatarSuccess(res) {
        this.ruleForm.picUrl = res.url;
      },
      //限制图片格式大小
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#goods-catalog {
  //内容填满
  height: 100%;
}
.el-header {
  line-height: 75px;
  height: 75px;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  .el-cascader-panel>div{
    width: 200px;
  }
</style>